package com.example.demo.serviceImpl.app;

import com.example.demo.dao.app.AppDao;
import com.example.demo.dao.task.TaskAppDao;
import com.example.demo.dao.user.EmployerAppDao;
import com.example.demo.po.app.App;
import com.example.demo.service.app.AppService;
import com.example.demo.service.user.UserService;
import com.example.demo.utils.Constant;
import com.example.demo.utils.FileHelper;
import com.example.demo.vo.app.AppVO;
import com.example.demo.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class AppServiceImpl implements AppService {
    private static final Logger logger = LoggerFactory.getLogger(AppServiceImpl.class);

    @Value("${web.app-upload-path}")
    private String path;
    @Resource
    private AppDao appDao;
    @Resource
    private TaskAppDao taskAppDao;
    @Resource
    private EmployerAppDao employerAppDao;
    @Resource
    private UserService userService;

    @Override
    public ResultVO<AppVO> uploadApp(MultipartFile app,String username) {
        try {
            AppVO appVO = FileHelper.saveApp(path, app);
            appDao.insertApp(appVO);
            App app1=appDao.selectAppByFile(appVO.getFile());
            employerAppDao.insertEmployerApp(userService.getUserByName(username).getUid(),app1.getAid());
            return new ResultVO<AppVO>(1, "应用上传成功", appVO);
        } catch (IOException ioException){
            logger.error("文件复制时出错", ioException);
        }
        return new ResultVO<>(-1, "服务器错误，请联系网站管理员。");
    }



    @Override
    public App getAppByTask(int tid) {
        return taskAppDao.selectAppByTask(tid);
    }

    @Override
    public ResultVO<List<AppVO>> getAppByEmployer(String username,int pageNum) {
        int pageSize=pageNum==-1?Constant.NO_PAGE_SIZE:Constant.DEFAULT_PAGE_SIZE;
        pageNum=pageNum==-1?1:pageNum;
        List<App> list=employerAppDao.selectAppByUser(username,pageNum, pageSize);
        if(list==null){
            return new ResultVO<>(-1,"用户没有上传app",null);
        }
        List<AppVO> appVOList=new ArrayList<>();
        for(App app:list){
            appVOList.add(new AppVO(app));
        }
        int fullPageNum=(employerAppDao.selectAppByUser(username,1,0).size()-1)/10+1;
        return new ResultVO<List<AppVO>>(1,pageNum+"/"+fullPageNum,appVOList);
    }

    @Override
    public void downloadFile(String originName, String newName, HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        response.setContentType("application/x-msdownload");
        try {
            org.springframework.core.io.Resource resource = FileHelper.loadFileAsResource(path, originName);
            if(resource == null)
                return;
            inputStream = resource.getInputStream();
            //1.设置文件ContentType类型
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = response.getOutputStream();
            //2.转码  UTF_8为传入的newName编码的格式 ISO_8859_1为浏览器默认编码
            String convertName = new String(newName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            //3.设置 header  Content-Disposition
            response.setHeader("Content-Disposition", "attachment; filename=" + convertName);
            int b = 0;
            byte[] buffer = new byte[2048];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    outputStream.write(buffer, 0, b);
                }
            }
        } catch (IOException e) {
            logger.error("文件下载时出错", e);
        } finally {
            try {
                if(inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                logger.error("输入流或输出流关闭时出错！", e);
            }
        }
    }
}
